package org.jeecg.modules.categories.service.impl;

import org.jeecg.modules.categories.entity.BlogCategories;
import org.jeecg.modules.categories.mapper.BlogCategoriesMapper;
import org.jeecg.modules.categories.service.BlogCategoriesService;
import org.jeecg.modules.articles.entity.BlogArticles;
import org.jeecg.modules.articles.mapper.BlogArticlesMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description: blog_categories
 * @Author: jeecg-boot
 * @Date:   2025-06-30
 * @Version: V1.0
 */
@Service
public class BlogCategoriesServiceImpl extends ServiceImpl<BlogCategoriesMapper, BlogCategories> implements BlogCategoriesService {

    @Resource
    private BlogArticlesMapper blogArticlesMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateArticleCount(String categoryId, int increment) {
        if (categoryId == null) {
            return;
        }
        
        // 使用SQL直接更新文章数量
        baseMapper.updateArticleCount(categoryId, increment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recalculateArticleCount(String categoryId) {
        if (categoryId == null) {
            return;
        }
        
        // 统计该分类下已发布的文章数量
        QueryWrapper<BlogArticles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("category_id", categoryId)
                   .eq("status", 1)  // 已发布状态
                   .eq("del_flag", 0); // 未删除
        
        Long count = blogArticlesMapper.selectCount(queryWrapper);
        
        // 更新分类的文章数量
        BlogCategories category = this.getById(categoryId);
        if (category != null) {
            category.setArticleCount(count.intValue());
            this.updateById(category);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void recalculateAllArticleCounts() {
        // 获取所有分类
        List<BlogCategories> categories = this.list();
        
        for (BlogCategories category : categories) {
            recalculateArticleCount(category.getId());
        }
    }
}
